/**
 * Created by Administrator on 2015/3/20.
 */
/**
 * Created by Administrator on 2015/3/18.
 */
var express = require('express');
var router = express.Router();
var wechat = require('wechat');
var da =  require('./dataaccess');
var fs = require('fs');

var configInfo = JSON.parse(fs.readFileSync(__dirname.replace('\lib', '')+'/config.json').toString());

router.use('/public', express.static('public'));

router.use('/wechat', wechat(configInfo.wechatConfig, function(req, res){
    var message = req.weixin;
    switch (message.MsgType){
        case 'event':
            switch(message.Event){
                case 'subscribe':
                    var replyStr = configInfo.aboutMessage;
                    break;
                case 'CLICK':
                    switch(message.EventKey){
                        case 'activity':
                            replyStr = configInfo.activityMessage;
                            break;
                        case 'apply':
                            replyStr = configInfo.applyMessage;
                            break;
                        case 'dance':
                            replyStr = configInfo.danceMessage;
                            break;
                        case 'guzheng':
                            replyStr = configInfo.guzhengMessage;
                            break;
                        case 'zhuchi':
                            replyStr = configInfo.zhuchiMessage;
                            break;
                        case 'taekwondo':
                            replyStr = configInfo.taekwondoMessage;
                            break;
                        case 'about':
                            replyStr = configInfo.aboutMessage;
                            break;
                    }
                    break;
            }
            res.reply(replyStr);
            break;
    }
}));

router.get('/apply', function (req, res) {
    res.sendFile(__dirname.replace('\lib', '')+'/view/apply.html');
});

router.post('/apply', function (req, res) {
    console.log(req.body);
    da.applyAdd(req.body, function(err, result){
        if(!err){
            res.redirect('/done');
        }else
            res.redirect('/apply/fail');
    });
});

router.get('/done', function (req, res) {
    res.sendFile(__dirname.replace('\lib', '')+'/view/done.html');
});

router.use('/applylist', function (req, res) {
   res.sendFile(__dirname.replace('\lib', '')+'/view/applylist.html');
});

router.use('/test', function(req, res){
    console.log(configInfo);
    res.send('done');
});

router.use('/', function (req, res) {
    res.send('Welcome to Mini Palace');
});

module.exports = router;